package com.vertxExample.starter;

import io.netty.util.internal.logging.InternalLogger;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.templ.thymeleaf.ThymeleafTemplateEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.Log4jLoggerFactory;

public class StaticFileVerticle extends AbstractVerticle {

	private static final Logger logger = LoggerFactory.getLogger(StaticFileVerticle.class);

	Router router;
	ThymeleafTemplateEngine thymeleafTemplateEngine;

	@Override
	public void start(Promise<Void> startPromise) throws Exception {
		Router router = Router.router(vertx);

		thymeleafTemplateEngine = ThymeleafTemplateEngine.create(vertx);
		// 1. 处理静态资源
		router.route("/*").handler(StaticHandler.create());

		router.route("/").handler(req -> {
			logger.error("进来了");
			JsonObject jsonObject = new JsonObject();
			jsonObject.put("name", "hello world from back engine");

			thymeleafTemplateEngine.render(jsonObject, "templates/index.html", bufferAsyncResult -> {
				if (bufferAsyncResult.succeeded()) {
					req.response()
						.putHeader("content-type", "text/html")
						.end(bufferAsyncResult.result());
				} else {
					req.response().end("error");
				}
			});

		});


		vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
			if (http.succeeded()) {
				startPromise.complete();
				System.out.println("HTTP server started on port 8888");
			} else {
				startPromise.fail(http.cause());
			}
		});
	}
}
